package com.xxxx.server.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxx.server.mapper.MenuMapper;
import com.xxxx.server.pojo.Admin;
import com.xxxx.server.pojo.Menu;
import com.xxxx.server.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

	@Autowired
	private MenuMapper menuMapper;

	@Autowired
	private RedisTemplate redisTemplate;

	/**
	 * 查询所有菜单
	 * @return
	 */
	@Override
	public List<Menu> getAllMenusByAdminId() {
		return menuMapper.getAllMenusByAdminId(((Admin)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId());
	}

	/**
	 * 查询菜单及角色
	 * @return
	 */
	@Override
	public List<Menu> getAllMenusWithRole() {
		return menuMapper.getAllMenusWithRole();
	}

	/**
	 * 根据用户ID查询菜单列表
	 * @return
	 */
	@Override
	public List<Menu> getMenusByAdminId() {
		//从SecurityContextHolder的上下文中获取admin的id
		Integer adminId = ((Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId();
		ValueOperations<String,Object> valueOperations = redisTemplate.opsForValue();
		//从redis中获取菜单数据
		List<Menu> menus = (List<Menu>)valueOperations.get("menu_" + adminId);
		//如果为空，则去数据库中获取
		if (menus == null){
			menus = menuMapper.getMenusByAdminId(adminId);
			//将数据设置到Redis中
			valueOperations.set("menu_" + adminId,menus);
		}
		return menus;
	}

	/**
	 *根据角色获取菜单列表
	 * @return
	 */
	@Override
	public List<Menu> getMenusWithRole() {
		return menuMapper.getMenusWithRole();
	}

	/**
	 * 查询所有菜单
	 * @return
	 */
	@Override
	public List<Menu> getAllMenus() {
		return menuMapper.getAllMenus();
	}
}
